# This test script performs the third of the benchmarks presented in
# the paper I am submitting to mobisys '10. The benchmark performs a
# sharpening, brightness adjustment, and contrast adjustment of the
# given input image using the specified scheduler. 
#
# The input images used in the paper can be found in testdata/percom.

from __future__ import with_statement
import sys
import scavenger
from time import sleep, time
from threading import Thread

# Check command line args.
if len(sys.argv) < 4 or not '-s' in sys.argv:
    print 'Usage: mobisys1.py imagefile -s scheduler [-t threads] [-i iterations]'
    sys.exit(1)

# Read in the image file.
with open(sys.argv[1], 'rb') as infile:
    image = infile.read()

# Find out which scheduler to use.
scheduler = sys.argv[sys.argv.index('-s') + 1]
if not scheduler in ('pc', 'tc', 'adaptive'):
    print 'Invalid scheduler. Valid values are pc, tc, and adaptive.'
    sys.exit(1)

# Check whether a number of test iterations is given.
iterations = 1
if '-i' in sys.argv:
    iterations = int(sys.argv[sys.argv.index('-i') + 1])

# Check whether a number of concurrent threads has been specified.
if '-t' in sys.argv:
    threads = int(sys.argv[sys.argv.index('-t') + 1])
else:
    threads = 2

# Sleep for a little while to make sure that we discover
# the available surrogates.
sleep(2.0)

@scavenger.lprofilescavenge('len(#0)', store=True)
def lsharpen(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    factor = 1.0 + float(factor)
    new_image = ImageEnhance.Sharpness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.lprofilescavenge('len(#0)', store=True)
def lbrightness(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.lprofilescavenge('len(#0)')
def lcontrast(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Contrast(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.gprofilescavenge('len(#0)', store=True)
def gsharpen(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    factor = 1.0 + float(factor)
    new_image = ImageEnhance.Sharpness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.gprofilescavenge('len(#0)', store=True)
def gbrightness(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.gprofilescavenge('len(#0)')
def gcontrast(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Contrast(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)', 'len(#0)', store=True)
def csharpen(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    factor = 1.0 + float(factor)
    new_image = ImageEnhance.Sharpness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)', 'len(#0)', store=True)
def cbrightness(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

@scavenger.aprofilescavenge('len(#0)', 'len(#0)')
def ccontrast(image, factor, id=None):
    from PIL import Image, ImageEnhance
    from StringIO import StringIO
    sio = StringIO(image)
    pil_image = Image.open(sio)
    new_image = ImageEnhance.Contrast(pil_image).enhance(factor)
    sio = StringIO()
    new_image.save(sio, pil_image.format, quality=95)
    return sio.getvalue()

functions = None
if scheduler == 'pc':
    functions = [lsharpen, lbrightness, lcontrast]
elif scheduler == 'tc':
    functions = [gsharpen, gbrightness, gcontrast]
else:
    functions = [csharpen, cbrightness, ccontrast]
function_names = ['sharpen', 'brightness', 'contrast']

class Worker(Thread):
    def __init__(self, functions, image, x):
        super(Worker, self).__init__()
        self._functions = functions
        self._image = image
        self._x = x
        self.happy = True

    def run(self):
        try:
            global function_names
            for x in range(0, len(self._functions)):
                self._image = self._functions[x](self._image, 0.75, id='%s%i'%(function_names[x], self._x))
        except:
            self.happy = False

# Run the test!
for y in range(0, iterations):
    start = time()
    workers = []
    try:
        for x in range(0, threads):
            w = Worker(functions, image, x + (y*threads))
            w.start()
            workers.append(w)
        for worker in workers:
            worker.join()
    except:
        print '-1',
    stop = time()

    # Check that all workers are happy.
    happy = True
    for worker in workers:
        if not worker.happy:
            happy = False
            break
    if not happy:
        print -1
    else:
        print stop - start

scavenger.shutdown()
